<template>
  <div class="page-content">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>数据配置</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <div class="inner-box">
        <h4 class="content-title">数据配置 <span style="font-size:15px;color:#555;font-weight:400">/ {{
          detail.keyDescribe }}</span></h4>
        <vue-json-editor class="mt-15" style="height:600px" v-model="data" ref="JsonEditor" :mode="'code'" lang="zh"
          @has-error="onError" @json-change="onJsonChange"></vue-json-editor>
        <div class="mt-15">
          <el-button type="primary" icon="el-icon-tickets" @click="onJsonSave(0)" :loading="loading">保存数据</el-button>
          <el-button type="primary" icon="el-icon-tickets" @click="onJsonSave(1)" :loading="loading">保存并退出</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import vueJsonEditor from 'vue-json-editor-fix-cn'
export default {
  components: {
    vueJsonEditor,
  },
  data() {
    return {
      schema: {
        type: 'object',
        title: '',
      },
      data: {},
      editor: null,
      loading: false,
      formSearch: {
        classKey: "",
      },
      temp: null,
      detail: {},
      isError: false,
    }
  },
  mounted() {
    this.editor = this.$refs.JsonEditor;
    this.formSearch.classKey = this.$route.query.classKey || "";
    this.getKeyValue();
  },
  methods: {
    // QueryKeyValue
    getKeyValue() {
      let params = this.func.depCopy(this.formSearch);
      this.loading = true;
      this.https("get", "/api/Values/ReadData", params).then(res => {
        this.loading = false;
        this.detail = res || {};
        try {
          this.data = JSON.parse(this.detail.values)
        } catch (error) {
          this.data = {};
        }
      }).catch(res => {
        this.loading = false;
      })
    },
    onJsonChange(value) {
      this.temp = value;
      this.isError = false;
    },
    onJsonSave(isExit) {
      let params = this.func.depCopy(this.detail);
      params.values = JSON.stringify(this.func.depCopy(this.data));
      if (this.isError) {
        this.func.message("error","当前有错误不能保存");
        return;
      }
      this.loading = true;
      this.https("post", "/api/Values/SaveData", params).then(res => {
        this.loading = false;
        this.func.message("success","保存成功");
        if (isExit) {
          this.$router.go(-1);
        }
      }).catch(res => {
        this.loading = false;
      })
    },
    onError(error) {
      // error = error + "";
      // if (error.indexOf("Parse error on line 1") >= 0) {
      //   this.data = this.temp;
      // }
      this.isError = true;
    },
  }

}
</script>
<style lang="scss">
.jsoneditor-vue {
  height: 100%;
}

div.jsoneditor-menu a.jsoneditor-poweredBy {
  display: none !important;
}
</style>